from django.shortcuts import render
from rest_framework import mixins
from rest_framework import status
from rest_framework.generics import CreateAPIView,RetrieveAPIView,UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action

from . import serializers
from .models import User
from . import constants
# Create your views here.
#url(r'^users/$',view.UserView.as_view()),

class UserBrowsingHistoryView(CreateAPIView):
    '''添加用户浏览记录'''
    #只有登录用户才能操作用户浏览记录
    permission_classes = [IsAuthenticated]
    #指定序列化器
    serializer_class = serializers.UserBrowsingHistorySerializer

class AddressViewSet(mixins.CreateModelMixin,mixins.UpdateModelMixin, GenericViewSet):
     '''收货地址：增删改查


     '''
     # 指定序列化器
     serializer_class = serializers.UserAddressSerializer
     #指定权限
     permission_class = [IsAuthenticated]

     def create(self,request,*args, **kwargs):
         '''实现地址新增'''

         # 判断用户地址数量是否超过上线
         count = request.user.addresses.count()
         # count = Address.objects.filter(user=request.user).count()
         if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
             return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)
         #调用父类的create()方法实现以下逻辑
         return super().create(request,*args, **kwargs)
         # #创建序列化器
         # serializer = self.get_serializer(data=request.data)
         #
         #
         # #开启验证
         # serializer.is_valid(raise_exception=True)
         #
         # #保存数据
         # serializer.save()
         # #响应结果
         # return Response(serializer.data,status=status.HTTP_201_CREATED)

     def get_queryset(self):
         return self.request.user.addresses.filter(is_deleted=False)

         # GET /addresses/

     def list(self, request, *args, **kwargs):
         """
         用户地址列表数据
         """
         queryset = self.get_queryset()
         serializer = self.get_serializer(queryset, many=True)
         user = self.request.user
         return Response({
             'user_id': user.id,
             'default_address_id': user.default_address_id,
             'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
             'addresses': serializer.data,
         })

         # delete /addresses/<pk>/

     def destroy(self, request, *args, **kwargs):
         """
         处理删除
         """
         address = self.get_object()

         # 进行逻辑删除
         address.is_deleted = True
         address.save()

         return Response(status=status.HTTP_204_NO_CONTENT)

         # put /addresses/pk/status/

     @action(methods=['put'], detail=True)
     def status(self, request, pk=None):
         """
         设置默认地址
         """
         address = self.get_object()
         request.user.default_address = address
         request.user.save()
         return Response({'message': 'OK'}, status=status.HTTP_200_OK)

     # put /addresses/pk/title/
     # 需要请求体参数 title
     @action(methods=['put'], detail=True)
     def title(self, request, pk=None):
         """
         修改标题
         """
         address = self.get_object()
         serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
         serializer.is_valid(raise_exception=True)
         serializer.save()
         return Response(serializer.data)

class EmailView(UpdateAPIView):
    '''添加,更新邮箱'''
    serializer_class = serializers.EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user



class UserDetailView(RetrieveAPIView):
    '''个人用户中心基本信息'''
    #指定序列化器类
    serializer_class = serializers.UserDetailSerializer
    #指定权限,只有登录用户可以访问
    permission_classes = [IsAuthenticated]

    #指定查询集
    #queryset = User.objects.all()
    def get_object(self):
        '''重写该方法，返回序列化器要序列化的登录用户信息'''
        #只要视图中加了IsAuthenticated权限，self.request.user出来的结果，一定是登录用户信息
        return self.request.user

    #到目前为止,还没有出现要查询的登录用户对象信息



class UserView(CreateAPIView):
    '''注册'''
    #指定序列化器类
    serializer_class = serializers.UserSerializer






# url(r'^mobile/(?P<mobile>1[3-9]\d{9}/count/$',views.MobileCountView.as_view()),
class MobileCountView(APIView):
    '''判断手机号是否重复注册'''
    def get(self,request,mobile):

        #用username作为条件查询记录是否存在
        count = User.objects.filter(mobile=mobile).count()

        #序列化
        data = {
            'mobile':mobile,
            'count':count

        }
        #响应结果
        return Response(data)

# url(r'^usernames/(?<username>\w{5,20}/count/$',views.UsernameCountView.as_view()),


class UsernameCountView(APIView):
    '''判断用户是否重复注册'''
    def get(self,request,username):

        #用username作为条件查询记录是否存在
        count = User.objects.filter(username=username).count()

        #序列化
        data = {
            'username':username,
            'count':count

        }
        #响应结果
        return Response(data)